<template>
  <view class="wrapper">
    <!-- 收货信息 -->
    <view class="shipment">
      <view v-if="address" @click="getAddress">
      <view class="dt">收货人:</view>
      <view class="dd meta">
        <text class="name">{{address.userName}}</text>
        <text class="phone">{{address.telNumber}}</text>
      </view>
      <view class="dt">收货地址:</view>
      <view class="dd">{{adr}}</view>
      </view>
      <!-- 点击获取收货地址 -->
      <button v-else @click="getAddress">获取收货地址</button>
    </view>
    <!-- 购物车 -->
    <view class="carts">
      <view class="item">
        <!-- 店铺名称 -->
        <view class="shopname">优购生活馆</view>
        <!-- 遍历购物车的商品 -->
        <view class="goods"
        v-for="(item,i) in carts"
        :key="item.goods_id">
          <!-- 商品图片 -->
          <image class="pic" :src="item.goods_small_logo" />
          <!-- 商品信息 -->
          <view class="meta">
            <view class="name">{{item.goods_name}}</view>
            <view class="price">
              <text>￥</text>{{item.goods_price}}
              <text>.00</text>
            </view>
            <!-- 加减 -->
            <view class="amount">
              <text @click="changeCount(i,-1)" class="reduce">-</text>
              <input type="number" v-model="item.goods_count" class="number" />
              <text @click="changeCount(i,1)" class="plus">+</text>
            </view>
          </view>
          <!-- 选框 -->
          <view class="checkbox">
            <icon type="success" size="20"
            :color="item.goods_checked?'#ea4451':'#ccc'"
            @click="selectPrd(i)"></icon>
          </view>
        </view>
      </view>
    </view>
    <!-- 其它 -->
    <view class="extra">
      <label class="checkall" @click="selAll">
        <icon type="success" :color="isSleAll?'#ea4451':'#ccc'" size="20"></icon>全选
      </label>
      <view class="total">
        合计:
        <text>￥</text>
        <label>{{amountRe}}</label>
        <text>.00</text>
      </view>
      <!-- 创建订单 -->
      <view @click="createOrder" class="pay">结算({{selectedPrd.length}})</view>
    </view>
  </view>
</template>

<script>
export default {
  data () {
    return {
      // 购物车数据
      carts: [],
      // 收货地址
      address: null
    }
  },
  computed: {
    // 商品是否全选
    isSleAll () {
      return this.carts.every(item => item.goods_checked);
    },
    // 当前选中的商品
    selectedPrd () {
      return this.carts.filter(item => item.goods_checked);
    },
    // 总金额：选中的商品的总价
    // 普通方法-forEach
    amount () {
      let total = 0;
      this.selectedPrd.forEach(item => total += item.goods_count * item.goods_price);
      console.log('总价格',total);
      return total;
    },
    // 进阶方法-reduce
    amountRe () {
      // acc 累加器
      // cur 当前项
      // 默认值0，一定要给默认值，不然要判断
      return this.selectedPrd.reduce((acc,cur) => acc + cur.goods_price * cur.goods_count, 0);
    },
    // 收货详细地址
    adr () {
      if (this.address) {
        // 解构出来需要的数据
        const {provinceName, cityName, countyName, detailInfo} = this.address;
        return provinceName + cityName + countyName + detailInfo;
      }
    }
  },
  onShow () {
    this.getCarts();
    console.log('页面显示', this.selectedPrd);
  },
  onLoad () {
    
  },
  methods: {
    // 创建订单
    async createOrder () {
      // 创建条件
      // 1.有收货地址且购物车至少选中一件商品
      // 2.必须要登录
      if (!this.address || !this.selectedPrd.length) {
        return uni.showToast({
          title: '请选择收货地址或至少选中一件商品',
          duration: 1000,
          icon: 'none' // 文字比较多的时候可以把icon关掉
        });
      }
      // 根据token判断是否登录
      if (!uni.getStorageSync('hm_token')) {
        uni.showToast({
          title: '请登录',
          duration: 1000,
          icon: 'none'
        });
        // 跳转到登录页面
        return uni.navigateTo({
          url: '/packone/auth/index'
        });
      }
      // 创建订单
      const {msg:{msg,status},data} = await this.request({
        url: '/api/public/v1/my/orders/create', 
        method: 'POST',
        data: {
          // 订单的总价
          order_price: this.amountRe,
          // 收货地址
          consignee_addr: this.adr,
          // 购物车所购商品
          goods: this.selectedPrd.map(item => {
            item.goods_number = item.goods_count;
            return item;
          })
        },
        header: {
          Authorization: uni.getStorageSync("hm_token") //自定义请求头信息
        }
      });
      console.log('创建订单', msg,data);
      if (status === 200) {
        // 创建订单成功
        // 1.清空选中商品
        uni.removeStorageSync('carts');
        // 获取未选中商品
        let unSelPrd = this.carts.filter(item => !item.goods_checked);
        if (unSelPrd.length) {
          uni.setStorage({
            key: 'carts',
            // 把剩下的没有结算的存到本地
            data: unSelPrd
          });
        }
        // 2.跳转到订单页面
        uni.navigateTo({
           url: '/packone/order/index'
        });
      } else {
        uni.showToast({
          // title: msg
        });
      }
      
    },
    // 获取收货地址
    getAddress () {
      uni.chooseAddress({
        success: res => {
          // 箭头函数才能取到外面的this
          console.log(res);
          this.address = res;
        }
      });
    },
    getCarts () {
      this.carts = uni.getStorageSync('carts') || [];
    },
    // 购物车商品数量加减操作
    // step:步长，-1和1
    // i:当前商品的索引
    changeCount (i, step) {
      console.log(i,step);
      // 限制：加不能大于库存，减最小是1
      // 获取当前点击商品的数量
      const curCount = this.carts[i].goods_count;
      // 库存
      let kc = 10;
      if (step === 1 && curCount >= kc) {
        return uni.showToast({
          title: '没货了',
          duration: 1000
        });
      } else if (step === -1 && curCount === 1) {
        return uni.showToast({
          title: '数量不能再减了',
          duration: 1000
        });
      }
      // 加减操作
      this.carts[i].goods_count += step;
      // 更新本地数据
      this.updateCarts();
    },
    // 更新购物车本地数据
    updateCarts() {
      uni.setStorage({
        key: 'carts',
        data: this.carts
      });
    },
    // 商品单选,取反,同步数据
    selectPrd (i) {
      this.carts[i].goods_checked = !this.carts[i].goods_checked;
      this.updateCarts();
    },
    // 处理全选
    selAll () {
      // 1.如果全部选中，点击全选就全部选不中
      // 2.不是全选状态，点击全选就全部选中
      if (this.isSleAll) {
        this.carts.forEach(item => item.goods_checked = false);
      } else {
        this.carts.forEach(item => item.goods_checked = true);
      }
      // 同步本地数据
      this.updateCarts();
    }
    
  }
};
</script>

<style scoped lang="scss">
.shipment {
  height: 100rpx;
  line-height: 2;
  padding: 30rpx 30rpx 40rpx 30rpx;
  font-size: 27rpx;
  color: #333;
  background-color: #fff;
  background-image: url(http://static.botue.com/ugo/images/cart_border%402x.png);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: bottom;

  .dt {
    width: 140rpx;
    float: left;
    clear: both;
  }

  .dd {
    padding-left: 160rpx;
  }

  .meta {
    padding-right: 50rpx;
  }

  text.phone {
    float: right;
  }
}

.carts {
  background-color: #f4f4f4;
  padding-bottom: 110rpx;
  overflow: hidden;

  .shopname {
    padding: 30rpx;
    margin-top: 20rpx;
    font-size: 30rpx;
    color: #333;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    border-bottom: 1rpx solid #eee;
  }

  .goods {
    display: flex;
    padding: 30rpx 20rpx 30rpx 0;
    margin-left: 100rpx;
    border-bottom: 1rpx solid #eee;
    background-color: #fff;

    position: relative;

    .checkbox {
      width: 101rpx;
      height: 100%;
      background-color: #fff;

      display: flex;
      justify-content: center;
      align-items: center;

      position: absolute;
      left: -100rpx;
      top: 0;
    }

    &:last-child {
      border-bottom: none;
    }

    .pic {
      width: 200rpx;
      height: 200rpx;
      margin-right: 30rpx;
    }

    .meta {
      flex: 1;
      font-size: 27rpx;
      color: #333;
      position: relative;
    }

    .name {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price {
      position: absolute;
      bottom: 0;

      color: #ea4451;
      font-size: 33rpx;

      text {
        font-size: 22rpx;
      }
    }

    .amount {
      position: absolute;
      bottom: 0;
      right: 20rpx;

      height: 48rpx;
      text-align: center;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;

      display: flex;
      align-items: center;

      text {
        display: block;
        width: 60rpx;
        line-height: 48rpx;
        font-size: 36rpx;
        color: #ddd;
        text-align: center;
      }

      input {
        width: 60rpx;
        height: 48rpx;
        min-height: 48rpx;
        font-size: 27rpx;
        border-left: 1rpx solid #ddd;
        border-right: 1rpx solid #ddd;
      }
    }
  }
}

.extra {
  position: fixed;
  bottom: 0;
  /* #ifdef H5 */
  bottom: 50px;
  /* #endif */
  left: 0;
  z-index: 9;

  width: 750rpx;
  height: 96rpx;
  text-align: center;
  line-height: 96rpx;
  font-size: 36rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
  color: #333;
  display: flex;

  .checkall {
    width: 140rpx;
    line-height: 1;
    margin-left: 25rpx;
    display: flex;
    align-items: center;

    icon {
      margin-right: 20rpx;
    }
  }

  .total {
    display: flex;
    justify-content: center;
    flex: 1;

    label,
    text {
      color: #ea4451;
      vertical-align: bottom;
      position: relative;
      bottom: -2rpx;
    }

    text {
      position: relative;
      bottom: -3rpx;
      font-size: 24rpx;

      &:first-child {
        margin-left: 10rpx;
      }
    }
  }

  .pay {
    width: 200rpx;
    background-color: #ea4451;
    color: #fff;
  }
}
</style>

